package com.apes.scm.invoice.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.scm.account.res.model.Currency;
import com.apes.scm.account.res.repository.CurrencyRepository;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * 功能：账单明细
 *
 * @author xul
 * @create 2018-01-27 11:23
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = InvoiceItem.CONST_TABLE_NAME)
public class InvoiceItem extends BaseModel {
    public static final String CONST_TABLE_NAME = "acc_invoice_item";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "账单明细")
    @Comment("账单明细单号")
    private long id;

    @ManyToOne(optional = false,fetch = FetchType.LAZY,cascade = {CascadeType.ALL})
    @JoinColumn(name="invoice_id", referencedColumnName="id", nullable = false)
    @Comment("账单单号")
    private Invoice invoice;

    @Transient
    private PartyRole company; //公司

    public PartyRole getCompany() {
        return invoice != null ? invoice.getCompany() : null;
    }

    @Column(name = "name", length = 4000)
    @Comment("说明")
    private String name;

    @Column(name = "price_unit", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("单价")
    private double priceUnit = 0;

    @Column(name = "qty", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("数量")
    private double qty = 0;

    @Column(name = "freeze_Qty", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("冻结数量")
    private double freezeQty = 0;

    public void changeFreezeQty(double freezeQty) {
        if (this.getInvoice().getState() == 1) {
            throw new RuntimeException("帐单已冻结，不允许结算！");
        }
        if (this.getInvoice().getState() == 2) {
            throw new RuntimeException("帐单已冲销，不允许结算！");
        }
        this.freezeQty += freezeQty;
        //去除判断，因执行不通过
        if(Math.abs(this.freezeQty + qty) != Math.abs(this.freezeQty) + Math.abs(this.qty)) throw new RuntimeException("冻结数量有误！");
        if(Math.abs(this.freezeQty) > Math.abs(this.qty)) {
            throw new RuntimeException("源单号：" + this.getOrigin() + " 账单明细号:" + this.getId() +  " 已结算数量不能大于单据数量！");
        }
    }


    @Column(name = "settled_Qty", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("已结算数量")
    private double settledQty = 0;

    public void changeSettledQty(double settledQty) {
        if (this.getInvoice().getState() == 1) {
            throw new RuntimeException("帐单已冻结，不允许结算！");
        }
        if (this.getInvoice().getState() == 2) {
            throw new RuntimeException("帐单已冲销，不允许结算！");
        }
        this.settledQty += settledQty;
        if(Math.abs(this.settledQty + this.qty) != Math.abs(this.settledQty) + Math.abs(this.qty)) throw new RuntimeException("已结算数量有误！");
        //去除判断，因执行不通过
        if(Math.abs(this.settledQty) > Math.abs(this.qty)) {
            throw new RuntimeException("源单号：" + this.getOrigin() + " 账单明细号:" + this.getId() +  " 已结算数量不能大于单据数量！");
        }
    }


    @Transient
    private double pendingQty; // 待结算数量

    public double getPendingQty() {
        //去除判断，因执行不通过
        if(Math.abs(this.qty) < Math.abs(this.freezeQty) + Math.abs(this.settledQty)) throw new RuntimeException("源单明细：" + this.getOrigin() + "-" + this.getOriginItemId() +  " 冻结数量加上已结算数量不能大于单据数量！");
        return this.qty - this.freezeQty - this.settledQty;
    }


    @NotNull
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "product_uom_id", referencedColumnName = "id")
    @Comment("计量单位编码")
    private ProductUom uom;

    @Column(name = "amt_tax", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("税金")
    private double amtTax = 0; //税金

    @NotNull
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "tax_id", referencedColumnName = "id")
    @Comment("税率编码")
    private Tax tax;

    @Column(name = "amt_untaxed", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("未含税金额")
    private double amtUntaxed = 0;

    @Column(name = "price_subtotal", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("金额")
    private double priceSubtotal = 0;

    @Column(name = "discount", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("折扣")
    private double discount = 0;

    @Column(name = "floor_price", nullable = false, columnDefinition = ApesConst.FIELD_16_4_0)
    @Comment("底价")
    private double floorPrice = 0;

    @Comment("备注")
    @Column(name = "remark", length = 256)
    private String remark;  //备注

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="product_id", referencedColumnName="id", nullable = false)
    @Comment("商品")
    private Product product;

    @Transient
    private String originBusinessType; // 原始单类型

    public String getOriginBusinessType() {
        return invoice.getOriginBusinessType();
    }

    @Transient
    private String origin; // 原始单号

    public String getOrigin() {
        return invoice.getOrigin();
    }

    @Comment("源单据明细行")
    @Column(name = "origin_item_id", length = 30)
    private String originItemId;

    @Comment("来源单明细行")
    @Column(name = "source_item_id", length = 30)
    private String sourceItemId;


    @Column(name = "done", nullable =false, columnDefinition = "number(1,0) default 0")
    @Comment("是否完成")
    private boolean done = false;

    @Version
    @Column(name = "version", columnDefinition = "number(10) default 0")
    @Comment("版本号")
    private int version;  //JPA乐观锁


    /*
    * 更新完成状态
    * */
    public void updateDone() {
        if(this.getPendingQty() == 0) {
            this.setDone(true);
        }else {
            this.setDone(false);
        }
    }


    public void computeAmt() {
        Currency currency = this.getCompany().getParty().getCorporate().getCurrency();
        Map result = this.getTax().computeAll(this.getCompany(), currency, priceUnit, qty);
        amtTax = ((Double) result.get("taxAmt")).doubleValue();
        amtUntaxed = ((Double) result.get("totalExcluded")).doubleValue();
        priceSubtotal = ((Double) result.get("totalIncluded")).doubleValue();
    }

}
